package com.block.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.vo.ReqIpInfoVO;
import com.block.common.service.LogFactory;
import org.slf4j.Logger;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ALiIpUtil {

    private static Logger log = LogFactory.getCommLog();

    /**
     * 是境外ip
     * @param ip
     * @param appCode
     * @return
     */
    public static boolean isAbroadIp(String ip, String appCode){

        String host = "https://qryip.market.alicloudapi.com/lundear/qryip";
//        String appcode = "aff81d7303bb4573af4a83bfeada9683";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, Object> querys = new HashMap();
        querys.put("ip", ip);

        try {
            HttpRequest httpRequest = HttpUtil.createGet(host);
            httpRequest.headerMap(headers, true);
            httpRequest.form(querys);

            String response = httpRequest.execute().body();
//            log.info("【判断ip信息】【headers】{}【querys】{}【response】{}", JSON.toJSONString(headers), JSON.toJSONString(querys), response);

            System.out.println(response);
            JSONObject jsonObject = JSON.parseObject(response);
            Integer status = jsonObject.getInteger("status");

            if (status == 0){
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                String nation = adInfo.getString("nation");
                if (StrUtil.equals(nation, "中国")){
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 是境外ip
     * @param ip
     * @param areaArray
     * @return
     */
    public static boolean isTargetAreaIP(String ip, List<String> areaArray, String appCode){

        String host = "https://qryip.market.alicloudapi.com/lundear/qryip";
//        String appcode = "aff81d7303bb4573af4a83bfeada9683";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, Object> querys = new HashMap();
        querys.put("ip", ip);

        try {
            HttpRequest httpRequest = HttpUtil.createGet(host);
            httpRequest.headerMap(headers, true);
            httpRequest.form(querys);

            String response = httpRequest.execute().body();
            log.info("【判断ip信息】判断IP是不是给定地址【headers】{}【querys】{}【areaArray】{}【response】{}",
                    JSON.toJSONString(headers), JSON.toJSONString(areaArray), JSON.toJSONString(querys), response);

            System.out.println(response);
            JSONObject jsonObject = JSON.parseObject(response);
            Integer status = jsonObject.getInteger("status");

            if (status == 0){
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                String province = adInfo.getString("province");
                String city = adInfo.getString("city");
               if (areaArray.contains(province) || areaArray.contains(city)){
                   // 给定ip是否属于 给定的城市信息
                   return true;
               }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取ip的地址信息
     * @param reqIp
     * @param appCode
     * @return
     */
    public static ReqIpInfoVO getReqIpAreaInfo(String reqIp, String appCode) {

        ReqIpInfoVO reqIpInfoVO = new ReqIpInfoVO();
        reqIpInfoVO.setReqIp(reqIp);

        try {

            String host = "https://qryip.market.alicloudapi.com/lundear/qryip";
//        String appcode = "aff81d7303bb4573af4a83bfeada9683";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appCode);
            Map<String, Object> querys = new HashMap();
            querys.put("ip", reqIp);

            HttpRequest httpRequest = HttpUtil.createGet(host);
            httpRequest.headerMap(headers, true);
            httpRequest.form(querys);

            String response = httpRequest.execute().body();
            log.info("【获取ip地址信息】【headers】{}【querys】{}【response】{}",
                    JSON.toJSONString(headers), JSON.toJSONString(querys), response);

            System.out.println(response);
            JSONObject jsonObject = JSON.parseObject(response);
            Integer status = jsonObject.getInteger("status");

            if (status == 0){
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                String province = adInfo.getString("province");
                String city = adInfo.getString("city");
                String nation = adInfo.getString("nation");
                String district = adInfo.getString("district");
                String adcode = adInfo.getString("adcode");

                reqIpInfoVO.setNation(nation);
                reqIpInfoVO.setProvince(province);
                reqIpInfoVO.setCity(city);
                reqIpInfoVO.setArea(district);
                reqIpInfoVO.setAreaCode(adcode);

                // 需要处理行政区划代码(阿里云市场拉取的信息需要处理)
                if (StrUtil.isNotEmpty(adcode)){
                    reqIpInfoVO.setProvinceCode(StrUtil.fillAfter(StrUtil.sub(adcode, 0, 2), '0', 6));
                    reqIpInfoVO.setCityCode(StrUtil.fillAfter(StrUtil.sub(adcode, 0, 4), '0', 6));
                }

                reqIpInfoVO.setAreaInfo(StrUtil.format("{}-{}-{}-{}", nation, province, city, district));
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return reqIpInfoVO;
    }

}
